package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.DishFlavor;
import com.itheima.entity.SetmealDish;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        //删除redis菜品缓存数据
        String key="dish_"+dishDto.getCategoryId()+"*";
        Set keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);
        return R.success("添加成功");
    }

    /**
     * 菜品分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page<Dish> pageinfo = new Page<>(page, pageSize);
        Page<DishDto> dtoPage = new Page<>();
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Dish::getName, name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        dishService.page(pageinfo, queryWrapper); //查询玩之后pageinfo里面的属性会被附上值
        //拷贝
        BeanUtils.copyProperties(pageinfo, dtoPage, "records"); //将pageinfo拷贝给dtopage并忽略掉records属性

        List<Dish> dishList = pageinfo.getRecords();
        List<DishDto> dishDtoList = new ArrayList<DishDto>();
        for (Dish dish : dishList) {
            DishDto dishDto = new DishDto();
            //属性拷贝
            BeanUtils.copyProperties(dish, dishDto);
            //获取id
            Long categoryId = dish.getCategoryId();
            //通过id查寻名称
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                //赋值
                dishDto.setCategoryName(categoryName);
            }
            dishDtoList.add(dishDto);
        }
        dtoPage.setRecords(dishDtoList);
        return R.success(dtoPage);
    }

    /**
     * 根据id查询菜品信息和对应口味信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        R<DishDto> byIdWithFlavor = dishService.getByIdWithFlavor(id);
        return byIdWithFlavor;
    }

    /**
     * 修改菜品信息和对应口味信息
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {

        dishService.updateWithFlavor(dishDto);
        //删除redis菜品缓存数据
        String key="dish_"+dishDto.getCategoryId()+"*";
        Set keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);
        return R.success("修改成功");
    }

//    /**
//     *根据条件查询对应的菜品数据
//     * @param categoryId
//     * @return
//     */
//    @GetMapping("/list")
//    public R<List<Dish>> list(Long categoryId){
//        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(categoryId!=null,Dish::getCategoryId,categoryId);
//        //起售状态
//        queryWrapper.eq(Dish::getStatus,1);
//        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        List<Dish> list = dishService.list(queryWrapper);
//
//        return  R.success(list);
//    }

    /**
     * 根据条件查询对应的菜品数据
     *
     * @param
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish1) {
        List<DishDto> dishDtoList=null;
        String key="dish_"+dish1.getCategoryId()+"_"+dish1.getStatus();
        //先从redis中获取缓存数据
        dishDtoList = (List<DishDto>)redisTemplate.opsForValue().get(key);
        if(dishDtoList!=null){
            //如果存在,直接返回,无需查看数据库
            return R.success(dishDtoList);
        }
        //如果不存在，需要查询数据库，将数据库查询到的菜品数据缓存到redis
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish1.getCategoryId() != null, Dish::getCategoryId, dish1.getCategoryId());
        //起售状态
        queryWrapper.eq(Dish::getStatus, dish1.getStatus());
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);
        dishDtoList = new ArrayList<>();
        for (Dish dish : list) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            LambdaQueryWrapper<DishFlavor> dishFlavorQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorQueryWrapper.eq(dish.getId() != null, DishFlavor::getDishId, dish.getId());
            List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorQueryWrapper);

            dishDto.setFlavors(dishFlavorList);
            dishDtoList.add(dishDto);
        }
        redisTemplate.opsForValue().set(key,dishDtoList,1, TimeUnit.HOURS);
        return R.success(dishDtoList);
    }

    /**
     * 菜品批量停售起售
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable Integer status, @RequestParam List<Long> ids) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getId, ids);
        List<Dish> dishList = dishService.list(queryWrapper);
        for (Dish dish : dishList) {
            dish.setStatus(status);
        }
        dishService.updateBatchById(dishList);
        //清除所有缓存
        String key="dish_*";
        Set keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);
        return R.success("修改成功");
    }

    /**
     * 批量删除 要求删除菜品表和菜品口味表 前提条件此菜品不在套餐中
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        dishService.delete(ids);
        //清除所有缓存
        String key="dish_*";
        Set keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);
        return R.success("删除成功");
    }
}
